package com.study.chunguard.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author lifan
 * @date 2024/3/26 10:26
 */
public class IPHelper {

    private static final String UNKNOWN = "unknown";

    /**
     * 获取用户的真实ip地址 如果有多个就取第一个
     *
     * @param request http请求
     * @return 客户端ip
     */
    public static String getIpAddr(HttpServletRequest request) {

        if (request == null) {
            return null;
        }
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        String[] ips = ip.split(",");

        return ips[0].trim();
    }

    /**
     * 将IPV6转化为IPV4 否则采用原来的值
     *
     * @param ipvAddress ip地址
     * @return 转化后的地址
     */
    public static String convertIPv6ToIPv4(String ipvAddress) {
        try {
            InetAddress inet6Address = InetAddress.getByName(ipvAddress);
            if (inet6Address instanceof Inet6Address) {
                // 如果是IPv6地址
                Inet6Address inet6 = (Inet6Address) inet6Address;
                byte[] ipv4Bytes = new byte[4];
                System.arraycopy(inet6.getAddress(), 12, ipv4Bytes, 0, 4);
                InetAddress ipv4Address = InetAddress.getByAddress(ipv4Bytes);
                return ipv4Address.getHostAddress();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ipvAddress;
    }


}
